package com.jinlia.show.modules.system.controller.common;

import com.jinlia.show.modules.base.system.entity.File;
import com.jinlia.show.modules.base.system.service.FileMapperService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Matcher;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileUploadController {
    private final Logger logger = LoggerFactory.getLogger(FileUploadController.class);
    @Value("${file.uri}")
    public String fileUri;
    @Value("${file.local-uri}")
    public String localUri;
    @Value("${file.path}")
    public String filePath;
    //文件扩展名校验
    private List<String> contentTypeSuffix = Arrays.asList("IMAGE/PNG", "IMAGE/JPG", "IMAGE/JPEG", "IMAGE/GIF", "IMAGE/WEBP");

    @Autowired
    private FileMapperService fileMapperService;


    /**
     * 上次 图片
     * @param file 文件对象
     * @param secondPath  二级路径名称
     * @return
     */
    @SneakyThrows
    @RequestMapping("/upload/img")
    public File uploadImg(@RequestParam(value = "file", required = false) MultipartFile file,
                          @RequestParam(value = "secondPath", required = false) String secondPath)  {
        //校验文件类型
        if (!contentTypeSuffix.contains(file.getContentType().toUpperCase())) {
            throw new RuntimeException("不支持的图片类型" + file.getOriginalFilename());
        }
        String originalFilename = file.getOriginalFilename();
        java.io.File dest = new java.io.File(filePath + originalFilename);
        if (StringUtils.hasLength(filePath)){
            // 确保上传目录存在
            Path uploadPath = Paths.get(filePath + secondPath+ java.io.File.separator );
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            dest = new java.io.File(filePath  + secondPath + java.io.File.separator+originalFilename);
            originalFilename = secondPath+ "_" + originalFilename;

        }
        File myFile = fileMapperService.existName(originalFilename);
        if (Objects.nonNull(myFile)) {
            return myFile;
        }
        try {
            file.transferTo(dest);
            myFile = new File(originalFilename, localUri + originalFilename);
            fileMapperService.save(myFile);
        } catch (IOException e) {
            logger.error("上传图片失败", e);
            throw new RuntimeException("上传图片失败");
        }
        return fileMapperService.existName(originalFilename);
    }

    @RequestMapping("/get")
    public List<File> getFiles(@RequestBody File file) {
        return fileMapperService.getFiles(file);
    }

    @SneakyThrows
    @PostMapping("/base64")
    public File saveImage(@RequestBody ImageRequest request) {
        // 解码 base64 数据
        byte[] imageBytes = Base64.getDecoder().decode(request.getImageData());

        // 确保上传目录存在
        Path uploadPath = Paths.get(filePath);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String fileName = StringUtils.hasLength(request.getName()) ? request.getName() : "image-" + UUID.randomUUID();
        fileName = fileName + ".png";
        Path filePath = uploadPath.resolve(fileName);

        // 保存图片
        Files.write(filePath, imageBytes);

        return new File(fileName, localUri + fileName);

    }

    // 请求体 DTO
    public static class ImageRequest {
        private String name;
        private String imageData;
        private String secondPath;

        public String getImageData() {
            return imageData;
        }

        public void setImageData(String imageData) {
            this.imageData = imageData;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getSecondPath() {
            return secondPath;
        }

        public void setSecondPath(String secondPath) {
            this.secondPath = secondPath;
        }
    }

}
